package com.ty.superapi.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ty.superapi.dao.ProjectDao;
import com.ty.superapi.entity.Project;
import com.ty.superapi.entity.UserProject;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianyu
 * @since 2017-12-21
 */
@Service
public class ProjectService extends ServiceImpl<ProjectDao, Project> {

    @Autowired
    private UserProjectService userProjectService;

    /**
     * 查询用户加入的项目
     *
     * @param id
     * @return
     */
    public List<Map<String, Object>> selectByUserId(Integer id) {
        return baseMapper.selectByUserId(id);
    }

    /**
     * 新增或修改项目
     *
     * @param project
     * @param userIds
     * @return
     */
    public boolean put(Project project, String userIds) {
        List<UserProject> userProjectList = new ArrayList<UserProject>();
        String[] userIdArray = userIds.split(",");
        if (StringUtils.isEmpty(project.getId())) {
            project.setCreateDate(DateUtil.date());
            project.setUpdateDate(DateUtil.date());
            baseMapper.insertProject(project);
            for (String s : userIdArray) {
                UserProject userProject = new UserProject();
                userProject.setProjectId(project.getId());
                userProject.setUserId(Integer.valueOf(s));
                userProjectList.add(userProject);
            }
        } else {
            project.setUpdateDate(DateUtil.date());
            baseMapper.updateById(project);
            // 增删组员
            EntityWrapper<UserProject> entityWrapper = new EntityWrapper<UserProject>();
            entityWrapper.eq("project_id", project.getId());
            userProjectService.delete(entityWrapper);
            // 添加
            for (String s : userIdArray) {
                UserProject userProject = new UserProject();
                userProject.setUserId(Integer.valueOf(s));
                userProject.setProjectId(project.getId());
                userProjectList.add(userProject);
            }
        }
        return userProjectService.insertBatch(userProjectList);
    }

    /**
     * 查询项目信息
     *
     * @param id
     * @return
     */
    public Map<String, Object> selectById(Integer id) {
        Map<String, Object> map = BeanUtil.beanToMap(baseMapper.selectById(id));
        map.put("userIds", CollectionUtil.join(baseMapper.selectProMember(id), ","));
        return map;
    }

}
